import json

from apps.common.base.serializers import *
from apps.interface.node.models import *
from apps.interface.advert.serializers import AdvertBaseSerializer, AdvertModelSerializer
from django.apps import apps

class NodeBaseSerializer(BaseSerializer):

    class Meta:
        model = Node
        fields = "__all__"

class NodeModelSerializer(BaseSerializer):

    configDict = serializers.SerializerMethodField()
    def get_configDict(self, obj):
        configDict_def = {
            'coverUrl': '',
            'componentStyle': {'coverUrl':''},
            'itemStyle': {},
            'itemList': [
                {
                    'itemStyle': {},
                },
                {
                    'itemStyle': {},
                }
            ],
        }
        if obj.config:
            configDict = json.loads(obj.config)
            configDict['coverUrl'] = configDict.get('coverUrl') or configDict_def.get('coverUrl')
            configDict['componentStyle'] = configDict.get('componentStyle') or configDict_def.get('componentStyle')
            configDict['itemStyle'] = configDict.get('itemStyle') or configDict_def.get('itemStyle')
            configDict['itemList'] = configDict.get('itemList') or configDict_def.get('itemList')
        else:
            configDict = configDict_def
        return configDict


    componentModel = serializers.SerializerMethodField()
    def get_componentModel(self, obj):
        return {'id': obj.component.id, 'name': obj.component.name, 'title': obj.component.title} if obj.component else {}

    # advertList = serializers.SerializerMethodField()
    # def get_advertList(self, obj):
    #     _adverts = obj.adverts.order_by('-sort').select_related('item')
    #     if _adverts.exists():
    #         return AdvertModelSerializer(_adverts, many=True).data
    #     else:
    #         return []
    
    # itemList字段一定要加，否则前端itemList组件不会刷新数据
    # itemList = serializers.SerializerMethodField()
    # def get_itemList(self, obj):
    #     return [{}]

    class Meta:
        model = Node
        fields = ('id', 'sort', 'pageConfig', 'component', 'status', 'isShow', 'isTemplate', 'config',
                  'configDict', 'componentModel')